﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;

namespace CREAPA.Repositorio
{
  public class Contexto : IDisposable
    {
        private readonly SqlConnection minhaConexao;

        public Contexto()
        {
            minhaConexao = new SqlConnection(ConfigurationManager.ConnectionStrings["StringConexaosqlserver"].ConnectionString);  
            minhaConexao.Open();
            
        }
    
        public void ExecutaComando(string strQuery)
        {

            var cmdComando = new System.Data.SqlClient.SqlCommand

            {
                CommandText = strQuery,
                CommandType = CommandType.Text,
                Connection = minhaConexao

            };
            cmdComando.ExecuteNonQuery();
        }

        public void ExecutaComandoImagem(string login, byte[]imagem)
        {

            SqlCommand cmdComando = new SqlCommand("update Funcionario set Assinatura=@img where login=@login", minhaConexao);
            cmdComando.Parameters.Add("@img", SqlDbType.Image, imagem.Length).Value = imagem;
            cmdComando.Parameters.Add("@login", SqlDbType.NVarChar, 20).Value = login;

            cmdComando.ExecuteNonQuery();
        }

        public string ExecutaComandoComRetorno1Campo(string strQuery)
        {
            string retorno = null;
            var cmdComando = new System.Data.SqlClient.SqlCommand(strQuery, minhaConexao);

            SqlDataReader dr = cmdComando.ExecuteReader();
            if (dr.HasRows)
                if (dr.Read())
                    retorno = dr["retorno"].ToString().Trim();

            return retorno;
        }

        public SqlDataReader ExecutaComandoComRetorno(string strQuery)
        {
            var cmdComando = new System.Data.SqlClient.SqlCommand(strQuery, minhaConexao);
            return cmdComando.ExecuteReader();

        }


        public void Dispoded()
        {
            if (minhaConexao.State == ConnectionState.Open)
            {
                minhaConexao.Close();
                {

                }
            }
        }

        public void Dispose()
        {
            if (minhaConexao.State == ConnectionState.Open)
            {
                minhaConexao.Close();
                {

                }
            }
        }

    }
}
